﻿#region Using directives

using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

#endregion

namespace Weazel.Badger.Vhdl.LibraryFiles
{
  /// <summary>
  /// Enumeration of the embedded libraries
  /// </summary>
  public enum Libraries
  {    
    /// <summary>
    /// Contains prodecures to write std_logic_vector signals
    /// to file as hex, decimal (signed/unsigned) values.
    /// </summary>
    WeazelTextIo,
    StdLogicArithExt
  };

  public static class LibraryFiles
  {
    private static readonly string resourceLocation =
      "Weazel.Badger.Vhdl.LibraryFiles";

    public static string GetLibraryName(Libraries library)
    {
      switch (library)
      {
        case Libraries.WeazelTextIo: return "weazel_text_io";
        case Libraries.StdLogicArithExt: return "std_logic_arithext";

        default:
          throw new NotSupportedException("Unknown library");
      }
    }

    /// <summary>
    /// get the file name of an embedded library
    /// </summary>
    /// <param name="library"></param>
    /// <returns>Name of library file</returns>
    public static string GetLibraryFileName(Libraries library)
    {
      switch (library)
      {
        case Libraries.WeazelTextIo: return "weazel_text_io.vhd";
        case Libraries.StdLogicArithExt: return "std_logic_arithext.vhd";

        default:
          throw new NotSupportedException("Unknwon library");
      }
    }

    /// <summary>
    /// write a vhdl library file to a specific location on
    /// the disk.
    /// </summary>
    /// <param name="library">library to write</param>
    /// <param name="location">location on disk</param>
    public static void OuputLibraryFile(Libraries library, string location)
    {
      // get a stream to the embedded library file
      Assembly assembly = Assembly.GetExecutingAssembly();

      string resource = resourceLocation + "." + GetLibraryFileName(library);

      Stream stream = assembly.GetManifestResourceStream(resource);

      FileStream file = null;

      try
      {
        string path = location == null ?
          GetLibraryFileName(library) :
          location + "//" + GetLibraryFileName(library);

        // create a file on disk 
        file = File.Open(path, FileMode.Create);

        // write the content of the stream to the file
        byte[] buffer = new byte[(int)stream.Length];        
        int bytesRead = stream.Read(buffer, 0, (int)stream.Length);
                
        // TODO: Read returns 3 bytes of "junk" why ??
        file.Write(buffer, 3, bytesRead - 3);
      }
      catch (Exception e)
      {
        // 
        throw e;
      }
      finally
      {
        if (file != null)
          file.Close();
      }
    }
  }
}
